import categoryApi from '@/api/category';

// 初始化state的函数
const initState = () => ({
    category1Id: undefined,
    category2Id: undefined,
    category3Id: undefined,
    category1List: [],
    category2List: [],
    category3List: [],
});


const state = initState();
const actions = {
    async getCategory1List({ commit }) {
        try {
            let result = await categoryApi.getCategory1List();
            console.log(result);
            commit('SAVE_CATEGORY1_LIST', result.data);
            // this.category1List = result.data
            // console.log('获取到的数据',this.category1List);
        } catch (error) {
            console.log('获取一级分类数据失败');
        }
    },
    async getCategory2List({ commit, state }) {
        try {
            state.category2Id = undefined;
            state.category3Id = undefined;
            state.category2List = [];
            state.category3List = [];

            let result = await categoryApi.getCategory2List(state.category1Id);
            // this.category2List = result
            commit('SAVE_CATEGORY2_LIST', result.data);
        } catch (error) {
            console.log('获取二级分类数据失败', error);
        }
    },
    async getCategory3List({ commit, state }) {
        try {
            state.category3Id = undefined;
            state.category3List = [];
            let result = await categoryApi.getCategory3List(state.category2Id);
            // this.category3List = result
            commit('SAVE_CATEGORY3_LIST', result.data); 
        } catch (error) {
            console.log('获取三级分类数据失败');
        }
    },
};
const mutations = {

    SAVE_CATEGORY1_LIST(state, category1List) {
        state.category1List = category1List;
    },
    SAVE_CATEGORY2_LIST(state, category2List) {
        state.category2List = category2List;
    },
    SAVE_CATEGORY3_LIST(state, category3List) {
        state.category3List = category3List;
    },
};
const getters = {

};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
};
